package wsserver

import (
	"bufio"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"sync"

	"github.com/gorilla/websocket"
	"github.com/sirupsen/logrus"
	"inspur.com/cloudware/wscomm"
)

type Session struct {
	// sessionID indicates the unique id of session
	sessionID string

	// default is websocket
	tunnel SafeWriteTunneler
	// HostID---agentID; one host one agent
	AgentID  string
	connlock *sync.RWMutex
}

func (s *Session) String() string {
	return fmt.Sprintf("Tunnel session [%v]", s.sessionID)
}

func (s *Session) Serve() error {
	defer s.Close()

	for {
		t, r, err := s.tunnel.NextReader()
		if err != nil {
			logrus.Errorf("get %v reader error %v", s.String(), err)
			return err
		}
		if t != websocket.TextMessage {
			logrus.Errorf("Websocket message type must be %v type", websocket.TextMessage)
			return err
		}
		//读取我们自定义的通用消息类型
		message, err := ReadMessageFromTunnel(r)
		if err != nil {
			logrus.Errorf("Read message from tunnel %v error %v", s.String(), err)
			return err
		}
		logrus.Infof("Read message from host %v", message.AgentID)
		if message.MessageType == wscomm.Connect {
			logrus.Infof("Read connect request from host %v", message.AgentID)
		}

	}
}

func (s *Session) WriteMessageToTunnel(m *wscomm.Message) error {
	return s.tunnel.WriteMessage(m)
}

func (s *Session) Close() {
	s.tunnel.Close()
}
func ReadMessageFromTunnel(r io.Reader) (*wscomm.Message, error) {
	buf := bufio.NewReader(r)
	rawmessage, err := ioutil.ReadAll(buf)
	if err != nil {
		return nil, err
	}
	logrus.Infof("Receive Tunnel message Connectid")
	tunnelmessage := &wscomm.Message{}
	err = json.Unmarshal(rawmessage, tunnelmessage)
	if err != nil {
		return nil, err
	}
	return tunnelmessage, nil
}
